package com.iflytek.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iflytek.common.Result;
import com.iflytek.dao.GoodsDao;
import com.iflytek.document.GoodsDocument;
import com.iflytek.dto.GoodsDTO;
import com.iflytek.dto.PageDTO;
import com.iflytek.enums.GoodsRecommendEnum;
import com.iflytek.mapper.CategoryMapper;
import com.iflytek.mapper.GoodsMapper;
import com.iflytek.model.Category;
import com.iflytek.model.Goods;
import com.iflytek.service.GoodsService;
import com.iflytek.utils.CopyUtil;
import com.iflytek.vo.GoodsVO;
import com.iflytek.vo.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author h_t
 * @since 2023-09-23
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private CategoryMapper categoryMapper;

    /**
     * 获取推荐商品信息
     *
     * @return
     */
    @Override
    public Result<List<GoodsVO>> goodsRecommend() {

        List<GoodsVO> goodsVOList = new ArrayList<>();
        Iterable<GoodsDocument> all = goodsDao.findAll();
        List<GoodsDocument> goodsDocuments = new ArrayList<>();
        all.forEach(s->{
            goodsDocuments.add(s);
        });
//        if (!CollectionUtils.isEmpty(goodsDocuments)) {
//            List<GoodsDocument> collection = goodsDocuments.stream()
//                    //过滤出推荐状态的商品
//                    .filter(goodsDocument -> goodsDocument.getRecommend().equals(true))
//                    .collect(Collectors.toList());
//            goodsVOList = CopyUtil.copyList(collection, GoodsVO.class);
//        } else {
            QueryWrapper<Goods> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.lambda().eq(Goods::getSales, GoodsRecommendEnum.YES.getCode());
            objectQueryWrapper.orderByDesc("recommend");
//            PageHelper.startPage(1, 3);
            List<Goods> goods = goodsMapper.selectList(objectQueryWrapper);
            goodsVOList = CopyUtil.copyList(goods, GoodsVO.class);

//        }
        return Result.success(goodsVOList);
    }

    /**
     * 获取热销的商品
     *
     * @return
     */
    @Override
    public Result<List<GoodsVO>> goodsSales() {
        List<GoodsVO> goodsVOList = new ArrayList<>();
        Iterable<GoodsDocument> all = goodsDao.findAll();
        List<GoodsDocument> goodsDocuments = new ArrayList<>();
        all.forEach(s->{
            goodsDocuments.add(s);
        });
        if (!CollectionUtils.isEmpty(goodsDocuments)) {

            List<GoodsDocument> collection = goodsDocuments.stream().sorted(Comparator.comparingInt(GoodsDocument::getSales).reversed()).limit(8).collect(Collectors.toList());
            goodsVOList = CopyUtil.copyList(collection, GoodsVO.class);
        } else {
            QueryWrapper<Goods> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.lambda().eq(Goods::getRecommend, GoodsRecommendEnum.YES.getCode());
            objectQueryWrapper.orderByDesc("sales");
//            PageHelper.startPage(1, 3);
            List<Goods> goods = goodsMapper.selectList(objectQueryWrapper);
            goodsVOList = CopyUtil.copyList(goods, GoodsVO.class);

        }
        return Result.success(goodsVOList);
    }

    /**
     * 查询所有商品（非分页）
     * @return
     */
    @Override
    public Result<List<GoodsVO>> findAll() {
        List<GoodsVO> goodsVOS = new ArrayList<>();
        Iterable<GoodsDocument> all = goodsDao.findAll();
        List<GoodsDocument> goodsDocuments = new ArrayList<>();
        all.forEach(s->{
            goodsDocuments.add(s);
        });
        if (!CollectionUtils.isEmpty(goodsDocuments)){
            goodsVOS = CopyUtil.copyList(goodsDocuments, GoodsVO.class);
        }else {
            QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
            List<Goods> goods = goodsMapper.selectList(queryWrapper);
            goodsVOS = CopyUtil.copyList(goods, GoodsVO.class);
        }
        goodsVOS.forEach(s->{
            Category category = categoryMapper.selectById(s.getCategoryId());
            String name = category.getName();
            s.setCategoryName(name);
        });
        return Result.success(goodsVOS);
    }

    /**
     * 根据分类分页查询商品
     * @param pageDTO
     * @param categoryId
     * @return
     */
    @Override
    public Result<PageVO<GoodsVO>> findByCategory(PageDTO pageDTO, String categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(pageDTO.getName())) {
            queryWrapper.lambda().like(Goods::getName,pageDTO.getName());
        }
        if (pageDTO.getPageNum() == null) {
            pageDTO.setPageNum(1);
        }
        if (pageDTO.getSize() == null) {
            pageDTO.setSize(5);
        }
        PageHelper.startPage(pageDTO.getPageNum(),pageDTO.getSize());
        queryWrapper.lambda()
                .eq(Goods::getCategoryId,categoryId);
        List<Goods> goodsList = goodsMapper.selectList(queryWrapper);
        PageInfo<Goods> goodsPageInfo = new PageInfo<>();
        List<GoodsVO> goodsVOList = CopyUtil.copyList(goodsList,GoodsVO.class);
        PageVO<GoodsVO> pageVO = new PageVO<>();
        BeanUtils.copyProperties(pageDTO,pageVO);
        pageVO.setTotal(goodsPageInfo.getTotal());
        pageVO.setRecords(goodsVOList);
        return Result.success(pageVO);
    }

    /**
     * 获取最新商品
     * @return
     */
    @Override
    public Result<List<GoodsVO>> goodsNews() {
        List<GoodsVO> goodsVOList = new ArrayList<>();
        Iterable<GoodsDocument> all = goodsDao.findAll();
        List<GoodsDocument> goodsDocuments = new ArrayList<>();
        all.forEach(s->{
            goodsDocuments.add(s);
        });
        if (!CollectionUtils.isEmpty(goodsDocuments)) {
            List<GoodsDocument> collection = goodsDocuments.stream().sorted(Comparator.comparing(GoodsDocument::getCreateTime).reversed()).limit(8).collect(Collectors.toList());
            goodsVOList = CopyUtil.copyList(collection, GoodsVO.class);
        } else {
            QueryWrapper<Goods> objectQueryWrapper = new QueryWrapper<>();
            objectQueryWrapper.lambda().eq(Goods::getRecommend, GoodsRecommendEnum.YES.getCode());
            objectQueryWrapper.orderByDesc("create_time");
            PageHelper.startPage(1, 8);
            List<Goods> goods = goodsMapper.selectList(objectQueryWrapper);
            goodsVOList = CopyUtil.copyList(goods, GoodsVO.class);

        }
        return Result.success(goodsVOList);

    }

    /**
     * @param pageDTO
     * @return
     */
    @Override
    public Result<PageVO<GoodsVO>> goodsPage(PageDTO pageDTO) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(pageDTO.getName())) {
            queryWrapper.lambda().like(Goods::getName,pageDTO.getName());
        }
        if (pageDTO.getPageNum() == null) {
            pageDTO.setPageNum(1);
        }
        if (pageDTO.getSize() == null) {
            pageDTO.setSize(5);
        }
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getSize());
        List<Goods> goodss = goodsMapper.selectList(queryWrapper);
        PageInfo<Goods> pageInfo = new PageInfo<>(goodss);
        PageVO<GoodsVO> pageVO = new PageVO<>();
        BeanUtils.copyProperties(pageDTO, pageVO);
        List<GoodsVO> goodsVOS = CopyUtil.copyList(goodss, GoodsVO.class);
        pageVO.setTotal(pageInfo.getTotal());
        pageVO.setRecords(goodsVOS);
        return Result.success(pageVO);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result<Boolean> deleteId(Long id) {
        int deleteById = goodsMapper.deleteById(id);
        if (deleteById == 0) {
            return Result.error("401", "删除失败");
        }else {
            goodsDao.deleteById(id);
            return Result.success(true);
        }

    }

    /**
     * @param id
     * @return
     */
    @Override
    public Result<GoodsVO> getGoodsId(Long id) {
        Goods goods ;
        Optional<GoodsDocument> goodsDocument = goodsDao.findById(id);
        GoodsDocument document = goodsDocument.get();
        if (document != null){
            goods = CopyUtil.copy(document, Goods.class);
        }else {
            goods = goodsMapper.selectById(id);
        }
        if (ObjectUtils.isEmpty(goods)) {
            return Result.error("401", "找不到该书本！");
        }
        GoodsVO goodsVO = CopyUtil.copy(goods, GoodsVO.class);

        return Result.success(goodsVO);
    }

    /**
     * @param goodsDTO
     * @return
     */
    @Override
    public Result<Boolean> updateGoods(GoodsDTO goodsDTO) {
        if (goodsDTO == null) {
            return Result.error("2", "数据不能为空");
        }
        Goods goods = CopyUtil.copy(goodsDTO, Goods.class);
        int count = goodsMapper.updateById(goods);

        if (count > 0) {
            GoodsDocument copy = CopyUtil.copy(goods, GoodsDocument.class);
            goodsDao.save(copy);
            return Result.success(true);
        } else {
            return Result.error("1", "更新失败");
        }
    }

    /**
     * @param goodsDTO
     * @return
     */
    @Override
    public Result<Boolean> saveGoods(GoodsDTO goodsDTO) {
        if (goodsDTO == null) {
            return Result.error("2", "数据不能为空");
        }
        Goods goods = CopyUtil.copy(goodsDTO, Goods.class);

        int count = goodsMapper.insert(goods);

        if (count > 0) {
            GoodsDocument copy = CopyUtil.copy(goods, GoodsDocument.class);
            goodsDao.save(copy);
            return Result.success(true);
        }else {
            return Result.error("1","保存失败");
        }
    }


}